import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_yfree/YFree.dart';
import 'package:flutter_yim/YIM.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:pc/Const/IFinal.dart';
import 'package:pc/Model/UserModel.dart';
import 'package:pc/Util/App/AppUtils.dart';
import 'package:pc/Util/WindowUtils.dart';
import 'package:pc/Util/YOSS/YOSS.dart';
import 'package:system_tray/system_tray.dart';
import 'package:window_manager/window_manager.dart';

void openPage(YPage page) {
  yRunApp(
    launchPage: page,
    primarySwatch: Colors.deepOrange,
    onYConfig: () {
      YConfig.appName = "YShop客服端";
      YConfig.themeColor = Color.fromARGB(255, 255, 87, 34);
      YConfig.imagePlaceHolder = "images/loading.png";
      YConfig.onHttpHeader = () async {
        return {
          "app-platform-isweb": yIsWeb ? "1" : "0",
          "app-platform-system": yIsWeb ? defaultTargetPlatform.name : Platform.operatingSystem,
          "app-platform-version": yIsWeb ? null : Platform.operatingSystemVersion,
          "app-version": (await PackageInfo.fromPlatform()).buildNumber,
          "app-sign": (await AppUtils.readUserModel())?.sign,
        };
      };
      YConfig.onYPostCommonError = (page, code, message, jkid, kv, callback, onModel, showProgress, showErrorToast, cacheEnable) async {
        if (!(await AppUtils.checkIsLogon(page, goLogin: true))) {
          callback.call(false, null, code!, message!);
          return;
        }
        page.yPost<UserModel>(IFinal.Jkids.refresh_sign, null, (isSuccess, results, code, message) {
          if (isSuccess) {
            AppUtils.saveUserModel(results!.first);
            page.yPost(jkid, kv, callback, onModel: onModel, showProgress: showProgress, showErrorToast: showErrorToast, cacheEnable: cacheEnable);
          } else {
            AppUtils.deleteUserModel();
            yShowBuilder("登录失效，请重新登录\n$message", () {
              AppUtils.reLaunchApp(goLogin: true);
            }, null, false, posTitle: "重新登录");
          }
        }, onModel: (map) => UserModel.fromJson(map), showProgress: true, showErrorToast: false, cacheEnable: false);
      };
    },
  );
}

void initSystemMenu() {
  WidgetsBinding.instance.platformMenuDelegate.setMenus([
    PlatformMenu(
      label: YConfig.appName,
      menus: [
        PlatformMenuItemGroup(
          members: [
            PlatformMenuItem(
              label: "欢迎使用",
              onSelected: () {
                yToast("欢迎使用${YConfig.appName}");
              },
            ),
          ],
        ),
      ],
    ),
  ]);
}

void initYIM() {
  YIM.init(
    YIMOption(
      appKey: IFinal.Configs_Local.third_sdk.yim.appKey,
      debug: false,
    ),
  );
}

void initYOSS() {
  YOSS.init(
    YOSSOption(
      ossEndpoint: IFinal.Configs_Local.third_sdk.oss.ossEndpoint,
      bucketName: IFinal.Configs_Local.third_sdk.oss.bucketName,
      accessKey: IFinal.Configs_Local.third_sdk.oss.accessKey,
      accessSecret: IFinal.Configs_Local.third_sdk.oss.accessSecret,
      expire: IFinal.Configs_Local.third_sdk.oss.expire,
    ),
  );
}

Future<void> initWindow() async {
  await windowManager.ensureInitialized();
  await windowManager.waitUntilReadyToShow(
    WindowOptions(
      title: YConfig.appName,
      titleBarStyle: defaultTargetPlatform == TargetPlatform.windows ? TitleBarStyle.normal : TitleBarStyle.hidden,
      size: const Size(860, 600),
      minimumSize: const Size(860, 600),
      windowButtonVisibility: true,
      center: true,
      backgroundColor: Colors.white,
      skipTaskbar: false,
    ),
    () async {
      await windowManager.show();
      await windowManager.focus();
    },
  );
  setWindowMethodHandler();
}

Future<void> initSystemTray() async {
  String path = Platform.isWindows ? 'images/app_icon.ico' : 'images/app_icon.png';
  final AppWindow appWindow = AppWindow();
  final SystemTray systemTray = SystemTray();
  await systemTray.initSystemTray(title: YConfig.appName, iconPath: path);
  final Menu menu = Menu();
  await menu.buildFrom([
    MenuItemLabel(label: '显示', onClicked: (menuItem) => appWindow.show()),
    MenuItemLabel(label: '隐藏', onClicked: (menuItem) => appWindow.hide()),
    MenuItemLabel(label: '退出', onClicked: (menuItem) => windowManager.destroy()),
  ]);
  await systemTray.setContextMenu(menu);
  systemTray.registerSystemTrayEventHandler((eventName) {
    switch (eventName) {
      case kSystemTrayEventClick:
        appWindow.show();
        break;
      case kSystemTrayEventRightClick:
        systemTray.popUpContextMenu();
        break;
    }
  });
}
